12 Base types

Published

March 18, 2025

Modified

March 18, 2025

Introduction

在R中,流传着这么一句话——R里的一切都是对象。但此对象非彼对象,前者指得是来自于S语言的base object,同我们研究的面向对象(OO object)不是一回事。

下面我们介绍如何区分base objectOO object及所有base object的类别。

Base VS OO objects

区分二者的三种方法:

  • is.object():base object返回FALSE,OO object返回TRUE
  • sloop::otype():base object返回base,OO object返回其他,如S3
  • attr():base object返回NULL,OO object返回class属性。
is.object(1:10)
#> [1] FALSE
is.object(mtcars)
#> [1] TRUE

sloop::otype(1:10)
#> [1] "base"
sloop::otype(mtcars)
#> [1] "S3"

attr(1:10, "class")
#> NULL
attr(mtcars, "class")
#> [1] "data.frame"

Base types

无论是OO object还是base object,都有一个base type,使用typeof()来查看;不要使用mode()storage.mode(),它们只适配S语言。

typeof(1:10)
#> [1] "integer"

typeof(mtcars)
#> [1] "list"

typeof(mean)
#> [1] "closure"

R 的底层使用了C语言中的switch语句来对不同base type执行不同处理。想要新增一个base type需要修改R-core,所以通常不会随意增加base type。截至目前一共有25种base type,下面按照本书中出现的顺序列举。

Vector

base Type C Type
NULL NILSXP
logical LGLSXP
integer INTSXP
double REALSXP
complex CPLXSXP
character STRSXP
list VECSXP
raw RAWSXP
typeof(NULL)
#> [1] "NULL"
typeof(1L)
#> [1] "integer"
typeof(1i)
#> [1] "complex"

Functions

base Type C Type function type
closure CLOSXP regular R functions
special SPECIALSXP internal functions
builtin BUILTINSXP primitive functions
typeof(mean)
#> [1] "closure"
typeof(`[`)
#> [1] "special"
typeof(sum)
#> [1] "builtin"

Environments

base Type C Type
environment ENVSXP
typeof(globalenv())
#> [1] "environment"

S4

base Type C Type
S4 S4SXP
mle_obj <- stats4::mle(function(x = 1) (x - 2)^2)
typeof(mle_obj)
#> [1] "S4"

Language components

base Type C Type
symbol SYMSXP
language LANGSXP
pairlist LISTSXP
expression EXPRSXP
typeof(quote(a))
#> [1] "symbol"
typeof(quote(a + 1))
#> [1] "language"
typeof(formals(mean))
#> [1] "pairlist"
typeof(expression(1 + 0:9))
#> [1] "expression"

Others

base Type C Type
externalptr EXTPTRSXP
weakref WEAKREFSXP
bytecode BCODESXP
promise PROMSXP
... DOTSXP
any ANYSXP

Numeric type

“numeric”在R中存在三种解读:

  • 某些地方,numericdouble的别名。例如as.numeric()as.double()等价,numeric()double()等价。

  • 在S3和S4系统中,“numeric”用作”integer type”或”double type”的缩写:

    sloop::s3_class(1)
    #> [1] "double"  "numeric"
    sloop::s3_class(1L)
    #> [1] "integer" "numeric"
  • is.numeric()用来检测那些行为类似number的对象。例如,因子的本质是”integer type”,但是没有number的行为(求取一个因子的均值毫无意义)。

    typeof(factor("x"))
    #> [1] "integer"
    is.numeric(factor("x"))
    #> [1] FALSE

本书中的numeric表示integerdouble

Back to top